

package com.hazelcast.internal.diagnostics;

import com.hazelcast.client.impl.operations.OperationFactoryWrapper;
import com.hazelcast.spi.impl.operationservice.Operation;
import com.hazelcast.spi.impl.operationservice.OperationFactory;
import com.hazelcast.spi.impl.operationservice.impl.operations.Backup;
import com.hazelcast.spi.impl.operationservice.impl.operations.PartitionIteratingOperation;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Converts an operation class into something readable.
 * <p>
 * In most cases the class name is sufficient, but there are certain
 * operations like {@link Backup} and {@link PartitionIteratingOperation} where
 * one needs to see inside the content of an operation.
 */
public final class OperationDescriptors {

    // the key is the name of the class as string, to prevent any class references being retained
    private static final ConcurrentMap<String, String> DESCRIPTORS = new ConcurrentHashMap<>();

    private OperationDescriptors() {
    }

    public static String toOperationDesc(Operation op) {
        Class<? extends Operation> operationClass = op.getClass();
        if (PartitionIteratingOperation.class.isAssignableFrom(operationClass)) {
            PartitionIteratingOperation partitionIteratingOperation = (PartitionIteratingOperation) op;
            OperationFactory operationFactory = partitionIteratingOperation.getOperationFactory();
            String desc = DESCRIPTORS.get(operationFactory.getClass().getName());
            if (desc == null) {
                Class<? extends OperationFactory> clazz = operationFactory.getClass();
                if (operationFactory instanceof OperationFactoryWrapper ofw) {
                    clazz = ofw.getOperationFactory().getClass();
                }
                desc = PartitionIteratingOperation.class.getSimpleName() + "(" + clazz.getName() + ")";
                DESCRIPTORS.put(clazz.getName(), desc);
            }
            return desc;
        } else
            if (Backup.class.isAssignableFrom(operationClass)) {
                Backup backup = (Backup) op;
                Operation backupOperation = backup.getBackupOp();
                String desc = DESCRIPTORS.get(backupOperation.getClass().getName());
                if (desc == null) {
                    desc = Backup.class.getSimpleName() + "(" + backup.getBackupOp().getClass().getName() + ")";
                    DESCRIPTORS.put(backupOperation.getClass().getName(), desc);
                }
                return desc;
            } else {
                return operationClass.getName();
            }
    }
}
